<template>
  <section>
    <div class="container">
      <div class="left_item">
        <div class="con">
          <el-card shadow="never">
            <cm-scroll>
              <div style="padding: 20px">
                <el-input
                  placeholder="输入关键字进行过滤"
                  v-model="filterText"
                  @input="searchUser"
                ></el-input>
                <el-tree
                  v-loading="loading"
                  class="filter-tree"
                  :props="defaultProps"
                  ref="tree"
                  highlight-current
                  v-show="filterText === ''"
                  lazy
                  :load="loadNode"
                  style="height: 670px"
                  node-key="id"
                  :default-expanded-keys="leftDefaultExpandKeys"
                  @node-click="handleNodeClick"
                  :expand-on-click-node="false"
                  :key="treeKey"
                  @node-expand="handleExpand"
                >
                  <span class="span-ellipsis" slot-scope="{ node, data }">
                    <span :title="node.label">{{ node.label }}</span>
                    <span
                      style="margin-left: 10px; color: #cececd"
                      v-if="data.type == 0"
                      >{{ data.number }}人</span
                    >
                  </span>
                </el-tree>
                <el-tree
                  node-key="id"
                  ref="treeLeftSearch"
                  v-show="filterText !== ''"
                  class="left_tree"
                  highlight-current
                  :data="searchUsers"
                  :expand-on-click-node="false"
                  @node-click="handleNodeClick"
                  :props="defaultProps"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span style="margin-left: 5px">{{ data.label }}</span>
                    <span
                      style="margin-left: 10px; color: #cececd"
                      v-if="data.type == 0"
                      >{{ data.number }}人</span
                    >
                  </span>
                </el-tree>
              </div>
            </cm-scroll>
          </el-card>
        </div>
      </div>
      <div class="right_item">
        <el-card
          style="margin-bottom: 10px; display: flex; justify-content: flex-end"
        >
          <!-- <div class="flex-box">
            <el-upload
              class="upload-demo"
              :action="imgHead"
              :headers="head"
              :accept="accept"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :show-file-list="false"
            >
              <el-button type="primary" icon="el-icon-upload2">导入</el-button>
            </el-upload>

            <el-button
              type="primary"
              @click="exportExcel"
              icon="el-icon-download"
              >导出</el-button
            >
          </div> -->

          <el-dialog
            title="导出联系人"
            @close="exportExcelFail"
            :visible.sync="exportExcelContact"
            width="30%"
          >
            <el-tree
              v-loading="loading"
              class="filter-tree"
              :props="defaultProps"
              ref="tree"
              highlight-current
              v-show="filterText === ''"
              lazy
              :load="loadNode"
              style="overflow:scroll"
              node-key="id"
              show-checkbox
              @check="chooseExport"
            >
              <span class="span-ellipsis" slot-scope="{ node, data }">
                <span :title="node.label">{{ node.label }}</span>
                <span
                  style="margin-left: 10px; color: #cececd"
                  v-if="data.type == 0"
                  >{{ data.number }}人</span
                >
              </span>
            </el-tree>
            <span slot="footer" class="dialog-footer">
              <el-button @click="exportExcelFail">取 消</el-button>
              <el-button type="primary" @click="sureExport">确 定</el-button>
            </span>
          </el-dialog>
        </el-card>

        <el-card class="box-card" shadow="never">
          <el-form
            ref="newMenu"
            :model="formInfo"
            label-width="120px"
            v-if="formInfo.type == 0"
          >
            <el-form-item label="部门名称:" prop="deptName">
              <el-input disabled v-model="formInfo2.deptName"></el-input>
            </el-form-item>
            <el-form-item label="部门Id:" prop="id">
              <el-input disabled v-model="formInfo2.id"></el-input>
            </el-form-item>
            <!-- <el-form-item
              v-if="formInfo.pid != 0"
              label="分管领导:"
              prop="leaderCustomId"
            >
              <user-select
                v-if="show"
                @getUser="getUser3"
                v-model="formInfo2.leaderCustomId"
              ></user-select>
            </el-form-item> -->
            <!-- <el-form-item
              v-if="formInfo.pid != 0"
              label="部门负责人:"
              prop="managerCustomId"
            >
              <user-select
                v-if="show"
                @getUser="getUser4"
                v-model="formInfo2.managerCustomId"
              ></user-select>
            </el-form-item> -->

            <el-form-item v-if="formInfo.pid != 0" label="排序:" prop="sort">
              <el-input-number
                v-model="formInfo2.sort"
                :min="0"
                label="描述文字"
              ></el-input-number>
            </el-form-item>

            <el-form-item style="margin-top: 20px">
              <el-button type="primary" @click="addOrganize">
                新增部门
              </el-button>
              <el-button type="primary" @click="addUser">新增用户</el-button>
              <el-dropdown @command="handleSortCommand" style="margin: 0 10px">
                <el-button type="primary">
                  排序
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="org">部门排序</el-dropdown-item>
                  <el-dropdown-item command="user">用户排序</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button type="primary" @click="saveOrganize">保存</el-button>
              <el-button type="danger" @click="deleteOri">删除</el-button>
              <el-dropdown @command="handleCommand" style="margin-left: 10px">
                <el-button type="danger">
                  删除部门信息
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="0"
                    >删除当前部门下的所有用户
                  </el-dropdown-item>
                  <el-dropdown-item :command="1"
                    >删除当前部门下级节点的所有用户信息
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </el-form>
          <el-form
            ref="newMenu"
            :model="currentTokenUser.user"
            label-width="120px"
            v-if="formInfo.type == 1"
          >
            <el-form-item style="width: 400px" label="姓名:" prop="name">
              <el-input v-model="currentTokenUser.user.name"></el-input>
            </el-form-item>
            <el-form-item style="width: 400px" label="手机号:" prop="mobile">
              <el-input
                disabled
                v-model="currentTokenUser.user.mobile"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item style="width: 400px" label="用户状态:" prop="status">
              <el-radio v-model="currentTokenUser.user.status" label="NORMAL">
                正常
              </el-radio>
              <el-radio v-model="currentTokenUser.user.status" label="STOP">
                停用
              </el-radio>
            </el-form-item> -->
            <el-form-item label="部门名称:">
              <div>
                {{ currentDeptName }}
              </div>
            </el-form-item>
            <el-form-item style="width: 400px" label="职位:" prop="job">
              <el-input v-model="currentTokenUser.user.job"></el-input>
            </el-form-item>
            <!-- <el-form-item style="width: 400px" label="用户来源:" prop="source">
              <el-input
                disabled
                :value="
                  currentTokenUser.user.source == 'DING' ? '钉钉' : '平台'
                "
              ></el-input>
            </el-form-item> -->
            <!-- <el-form-item
              style="width: 400px"
              label="秘书:"
              prop="secretaryUserIds"
            >
              <user-select
                @getUser="getUser5"
                v-if="show"
                isMulSelect
                v-model="currentTokenUser.user.secretaryUserUqIds"
              ></user-select>
            </el-form-item> -->
            <!-- <el-form-item
              style="font-weight: bold;"
              label="联系信息"
            ></el-form-item> -->
            <!-- <el-form-item class="input_content" label="昵称:">
              <el-input v-model="currentTokenUser.user.nickname"></el-input>
            </el-form-item>
            <el-form-item class="input_content" label="手机:">
              <el-input v-model="currentTokenUser.user.mobile"></el-input>
            </el-form-item>
            <el-form-item class="input_content" label="邮箱:">
              <el-input v-model="currentTokenUser.user.email"></el-input>
            </el-form-item>
            <el-form-item class="input_content" label="qq:">
              <el-input v-model="currentTokenUser.user.qq"></el-input>
            </el-form-item> -->
            <el-form-item style="margin-top: 20px; float: left">
              <!-- <el-button type="primary" @click="setRole">分配角色</el-button> -->
              <!-- <el-button
                type="primary" @click="appResource"
              >移动端资源分配
              </el-button -->
              <!-- > -->
              <el-button type="primary" @click="transfer">调动部门</el-button>
              <!-- <el-button
                type="primary" @click="newPersonnel"
              >员工档案
              </el-button> -->
              <!-- <el-button
                type="primary" @click="handleWorkGroup"
              >工作组
              </el-button
              >
              <el-button
                type="primary" @click="resetPassword"
              >重置密码
              </el-button> -->
              <el-button type="primary" @click="addNewMenu">保存</el-button>
              <el-button type="danger" @click="deleteUser">删除</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
    <el-dialog
      @close="fail"
      title="新增用户:"
      width="40%"
      :visible.sync="addUserStatus"
    >
      <el-form
        ref="form"
        :model="formInfo1"
        :rules="rules1"
        :gutter="10"
        label-width="100px"
      >
        <el-form-item label="姓名:" prop="name">
          <el-input
            placeholder="请输入姓名"
            v-model="formInfo1.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            placeholder="请输入手机号"
            v-model="formInfo1.mobile"
          ></el-input>
        </el-form-item>
        <el-form-item label="职务:" prop="job">
          <el-input placeholder="请输入职务" v-model="formInfo1.job"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="saveNewUser">保存</el-button>
        <el-button @click="fail">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      @close="failOrganize"
      title="调动部门:"
      width="25%"
      :visible.sync="transferStatus"
    >
      <el-row style="text-align: center">
        <el-card>
          <el-col :span="24">
            <el-cascader
              :show-all-levels="false"
              v-model="chooseOrigId"
              :options="departmentList"
              :props="setBuMenProperty"
              style="float: left"
              clearable
            ></el-cascader>
          </el-col>
          <el-col :span="24">
            <div style="margin: 20px 0; float: right">
              <el-button type="primary" @click="mobilizeOri"> 确定 </el-button>
              <el-button @click="failOrganize"> 取消 </el-button>
            </div>
          </el-col>
        </el-card>
      </el-row>
    </el-dialog>
    <!-- <el-dialog
      title="分配角色:"
      @close="selectedGroup = []"
      width="50%"
      :visible.sync="setRoleStatus"
    >
      <el-card class="box-card">
        <div v-for="group in groups" :key="group.id" class="text item">
          <div
            class="holder-style"
            @click="selectGroup(group)"
            :class="{ 'holder-active': group.isActive != false }"
          >
            {{ group.name }}
            <span
              style="display: inline-block;margin-left: 10px;"
              :class="{ 'check-style-unequal-width': group.isActive }"
            >
            </span>
            <br />
            【{{ group.description ? group.description : "无备注" }}】
          </div>
        </div>
        <span style="float: right;margin:10px 0 10px 10px">
          <el-button type="primary" @click="assigningRoles">保存</el-button>
          <el-button @click="setRoleStatus = false">取消</el-button>
        </span>
      </el-card>
    </el-dialog> -->
    <el-dialog
      @close="fail1"
      width="40%"
      title="新增部门:"
      :visible.sync="addOrganizeStatus"
    >
      <el-row>
        <el-col :span="24" style="padding-right: 10px">
          <el-form
            :rules="rulesOri"
            ref="formOrig"
            :model="formInfoOri"
            :gutter="10"
            label-width="120px"
          >
            <el-form-item label="部门名称：" prop="name">
              <el-input
                placeholder="请输入部门名称"
                v-model="formInfoOri.deptName"
              ></el-input>
            </el-form-item>
            <el-form-item label="上级：" prop="parentId">
              <el-cascader
                :show-all-levels="false"
                :options="rootMenus"
                v-model="formInfoOri.parentId"
                :props="setProperty"
                clearable
              ></el-cascader>
            </el-form-item>
            <!-- <el-form-item label="分管领导：" prop="leaderCustomId">
              <user-select
                v-if="show1"
                v-model="formInfoOri.leaderCustomId"
                @getUser="getUser1"
              ></user-select>
            </el-form-item> -->
            <!-- <el-form-item label="部门负责人：" prop="managerCustomId">
              <user-select
                v-if="show1"
                v-model="formInfoOri.managerCustomId"
                @getUser="getUser"
              ></user-select>
            </el-form-item> -->
            <el-form-item label="排序：" prop="sort">
              <el-input-number
                v-model="formInfoOri.sort"
                :min="0"
                label="描述文字"
              ></el-input-number>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <div slot="footer">
        <el-button type="primary" @click="addOri">保存</el-button>
        <el-button @click="fail1">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="部门/用户排序："
      width="900px"
      :visible.sync="sortDialogStatus"
    >
      <el-row>
        <el-card>
          <el-col v-if="sortGroups.length > 0" :span="24" style="padding: 20px">
            <draggable
              chosenClass="chosen"
              animation="400"
              v-model="sortGroups"
            >
              <div
                v-for="(item, index) in sortGroups"
                :key="index"
                class="sortCls"
              >
                <span style="font-size: 16px; cursor: move; color: #666666">
                  {{ item.deptName || item.name }}
                </span>
              </div>
            </draggable>
            <div style="float: right; margin: 10px 0 10px 10px">
              <el-button type="primary" @click="fixSort">确定</el-button>
              <el-button @click="sortDialogStatus = false">取消</el-button>
            </div>
          </el-col>
          <div v-if="sortGroups.length == 0" class="no-found-div">
            <p class="no-found-text">没有数据可进行排序!</p>
          </div>
        </el-card>
      </el-row>
    </el-dialog>
  </section>
</template>
<script>
import { mapGetters } from "vuex";
import _ from "lodash";
import draggable from "vuedraggable";
import tool from "@/libs/tool";
// import appResource from "./appPermission/appResource";

export default {
  name: "user",
  created() {
    // this.refreshLeftTreeData();
    this.getDepartment();
    this.getOrganizeUserRoot("ALL", 0, this.level, this.resolve);
  },
  watch: {
    // filterText(val) {
    //   this.$refs.tree.filter(val);
    // }
  },
  data() {
    let validPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      setTimeout(() => {
        if (!tool.isValidPhone(value)) {
          callback(new Error("请输入正确手机号码"));
        } else {
          callback();
        }
      }, 100);
    };
    return {
      // 上传配置
      imgHead: window.api.sysUploadUrl + "?path=meeting",
      head: {
        userRole: "ADMIN",
        token: window.sessionStorage.getItem("token")
      },
      accept: ".xls, .xlsx",
      appResourceStatus: false,
      loading: false,
      show: true,
      show1: true,
      sortGroups: [], //当前部门下的用户
      sortDialogStatus: false,
      currentTokenUser: {
        user: {
          secretaryUserIds: "",
          secretaryUserUqIds: ""
        },
        organizeNames: []
      },
      groups: [], //角色
      setBuMenProperty: {
        children: "children",
        label: "deptName",
        checkStrictly: true,
        value: "id"
      },
      setProperty: {
        children: "children",
        label: "deptName",
        checkStrictly: true,
        value: "id"
      },
      selectedGroup: [], //选中角色
      chooseOrigId: [], //选中部门
      //新增用户表单
      formInfo1: {
        name: "",
        // username: "",
        mobile: "",
        job: ""
      },
      //新增部门表单
      formInfoOri: {
        name: "",
        sort: "",
        leaderName: "",
        leaderUserId: "",
        managerName: "",
        managerUserId: "",
        parentId: "",
        managerCustomId: "",
        leaderCustomId: "",
        deleteFlag: "",
        id: "",
        deptName: ""
      },
      //修改部门
      formInfo2: {
        id: "",
        deptName: "",
        leaderName: "",
        leaderUserId: "",
        managerName: "",
        managerUserId: "",
        sort: "",
        leaderCustomId: "",
        managerCustomId: ""
      },
      departmentList: [], //部门列表 不包含用户
      setRoleStatus: false,
      addUserStatus: false,
      exportExcelContact: false,
      addOrganizeStatus: false,
      transferStatus: false,
      formInfo: "",
      filterText: "",
      treeKey: new Date().getTime(),
      organizeTree: [], //左侧tree
      defaultProps: {
        children: "children",
        label: "contactsDept",
        isLeaf: "leaf",
        disabled: function(data, node) {
          // console.log(data,node)
          return !node.isLeaf;
        }
      },
      rules1: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        username: [
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        mobile: [{ required: true, trigger: "blur", validator: validPhone }],
        job: [{ required: true, message: "请输入职务", trigger: "blur" }]
      },
      rulesOri: {
        deptName: [{ required: true, message: "请输入部门", trigger: "blur" }],
        id: [{ required: true, message: "请输入上级", trigger: "blur" }],
        // managerCustomId: [
        //   { required: true, message: "请输入部门负责人", trigger: "blur" }
        // ],
        leaderCustomId: [
          { required: true, message: "请输入分管领导", trigger: "blur" }
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }]
      },
      temAllUsers: [],
      resAllUsers: [],
      leftCacheDefaultExpandKeys: [], // 左侧树-默认展开keys集合 缓存
      leftDefaultExpandKeys: [], // 左侧树-默认展开keys集合
      searchUsers: [], // 搜索显示结果
      node: { data: { id: 0 } },
      resolve: null,
      userInfo: {},
      // 排序类型
      sortType: "",
      // 部门名称
      currentDeptName: ""
    };
  },
  computed: {
    ...mapGetters({
      userDetail: "userDetail",
      roleList: "roleList"
    }),
    //上级
    rootMenus() {
      let tem = _.cloneDeep(this.departmentList);
      tem.unshift({
        deptName: '添加顶级部门',
        id: 0
      })
      // tem.unshift({ pid: 0, name: "根节点" });
      return tem;
    },
    maxHeight() {
      return { height: this.clientHeight - 220 + "px" };
    }
  },

  methods: {
    // 导入前文件校验
    beforeUpload(file) {
      // console.log(file)
      let { name } = file;
      // 是否有文件后缀
      if(name.lastIndexOf('.') == -1){
        this.$message({
          message: `请上传${this.accept}类型文件`
        });
        return false
      }
      // 是否是符合要求的文件后缀
      let subIndex = name.lastIndexOf('.') - name.length;
      let type = name.substr(subIndex);
      // console.log(type)
      if (!this.accept.includes(type)) {
        this.$message({
          message: `请上传${this.accept}类型文件`
        });
        return false;
      }
      return true;
    },
    // 导入成功
    handleSuccess(response, file, fileList) {
      this.$message({
        message: "导入成功",
        type: "success"
      });
      // console.log(response, file, fileList);
    },
    // 导出选择
    chooseExport(p1, p2) {
      // console.log(p1,p2)
      let { checkedNodes } = p2;
      console.log(checkedNodes);
      console.log(JSON.stringify(checkedNodes));
    },
    /**
     * 描述：移动端资源分配确认
     * 时间： 2021/4/24
     */
    saveResource() {
      let tem = {
        userId: this.formInfo.origId,
        resourceIds: this.$refs.resource.currentArr
      };
      this.API.addResourceAppUser({ body: tem }).then(data => {
        this.$message.success("保存成功");
        this.appResourceStatus = false;
      });
    },
    /**
     * 描述：左侧搜索-文本改变触发事件
     * 时间： 2021/3/24
     */
    searchUser() {
      // this.loadNode({ level: 0 }, null);
      this.getConstantsAndPerson(null);
    },
    /**
     * 描述：懒加载数据
     * 时间： 2021/3/22
     */
    async loadNode(node, resolve) {
      // if (resolve) {
      //   // this.node = node;
      //   this.resolve = resolve;
      //   // 把子节点清空，否则下次加载时会直接往里push子节点导致重复
      //   this.node.childNodes = [];
      // }
      if (node.level === 0) {
        this.getOrganizeUserRoot("ALL", 0, node.level, resolve);
      } else if (node.level >= 1) {
        this.getOrganizeUserRoot("ALL", node.data.id, node.level, resolve);
      }
    },

    getConstantsAndPerson() {
      let tem = {
        keywords: this.filterText
      };

      this.API.getConstantsAndPersonById(tem).then(res => {
        if (res.data) {
          console.log("^^^^^^^^^", res.data);
          res.data.map(item => {
            this.resAllUsers = res.data;

            this.$set(item, "expanded", true);
          });
          this.setTemUserChildren(this.resAllUsers, 0, res.data);
        }
      });
    },

    // 获取组织用户-懒加载
    getOrganizeUserRoot(queryType, parentId, level, resolve) {
      let tem = {
        queryType: queryType,
        type: 1,
        parentId: parentId === undefined ? 0 : parentId,
        module: null,
        keywords: this.filterText
      };
      this.API.getContactsDept(tem).then(res => {
        if (res.data) {
          res.data.map(item => {
            if (item.id) {
              if (item.number != 0) {
                item.leaf = false;
              } else {
                item.leaf = true;
              }
            } else {
              item.leaf = true;
            }
            if (level == 0) {
              this.$set(item, "expanded", true);
            }
          });
        }
        if (resolve === null) {
          if (this.fdilterText) {
            this.searchUsers = res.data;
          }
        } else {
          if (
            this.temAllUsers &&
            level === 0 &&
            this.temAllUsers.length === 0
          ) {
            this.temAllUsers = res.data;
            if (res.data.length > 0) {
              this.getOrganize(res.data[0].id);
            }
          } else {
            this.setTemUserChildren(this.temAllUsers, parentId, res.data);
            console.log(2222222222);
          }
          resolve(res.data);
        }
        if (level === 0) {
          // this.setDefaultExpandLeftTree();
          if (res.data.length > 0) {
            this.$nextTick().then(() => {
              const firstNode = document.querySelector(".el-tree-node");
              firstNode.click();
            });
          }
        }
      });
    },
    /**
     * 描述：设置用户树子集
     * 时间： 2021/3/24
     */
    setTemUserChildren(data, parentId, subData) {
      if (data) {
        data.map(item => {
          if (item.id === parentId) {
            // console.log(item.children)
            if (item.children === undefined || item.children === null) {
              this.$set(item, "children", subData);
            }
          } else {
            if (item.children) {
              this.setTemUserChildren(item.children, parentId, subData);
            }
          }
        });
      }
    },
    /**
     * 描述：设置默认展开 第一级
     * 时间： 2021/3/25
     */
    setDefaultExpandLeftTree() {
      this.setLeftExpandKeys(this.resAllUsers);
      this.leftDefaultExpandKeys = this.leftCacheDefaultExpandKeys;
    },
    setLeftExpandKeys(data) {
      if (data) {
        data.map(item => {
          if (item.expanded) {
            // console.log(item.id, item.expanded)
            if (!this.checkCacheExpandKeyExisted(item.id)) {
              this.leftCacheDefaultExpandKeys.push(item.id);
            }
          } else {
            if (item.children) {
              this.setLeftExpandKeys(item.children);
            }
          }
        });
      }
    },
    /**
     * 描述：检测缓存展开的key是否存在
     * 时间： 2021/3/26
     */
    checkCacheExpandKeyExisted(id) {
      let result = false;
      if (this.leftCacheDefaultExpandKeys) {
        for (let item of this.leftCacheDefaultExpandKeys) {
          if (item === id) {
            result = true;
            break;
          }
        }
      }
      return result;
    },
    //重置密码
    resetPassword() {
      this.$confirm("确定重置当前用户的密码？", "提示", {})
        .then(() => {
          let userId = this.currentTokenUser.user.userId;
          this.API.resetPassword({ userId: userId }).then(() => {
            this.success("重置成功");
          });
        })
        .catch(() => {});
    },
    getUser(obj) {
      this.formInfoOri.leaderName = obj.userNames;
      this.formInfoOri.leaderUserId = obj.origId;
    },
    getUser1(obj) {
      this.formInfoOri.managerName = obj.userNames;
      this.formInfoOri.managerUserId = obj.origId;
    },
    getUser3(obj) {
      this.formInfo2.leaderName = obj.userNames;
      this.formInfo2.leaderUserId = obj.origId;
    },
    getUser4(obj) {
      this.formInfo2.managerName = obj.userNames;
      this.formInfo2.managerUserId = obj.origId;
    },
    getUser5(obj) {
      this.currentTokenUser.user.secretaryUserIds = obj.origId;
    },
    //保存部门信息
    saveOrganize() {
      let tem = _.cloneDeep(this.formInfo2);
      this.API.updateDept({ body: tem }).then(ret => {
        this.success("修改成功");
        this.refreshLeftTreeData();
      });
    },
    //新增员工档案
    newPersonnel() {
      const { origId: userId, id } = this.formInfo;
      this.$router.push({
        name: "newPersonnel",
        params: { userId: userId, id: id }
      });
    },
    //工作组
    handleWorkGroup() {
      let userId = this.formInfo.origId;
      let userName = this.formInfo.name;
      this.$router.push({
        name: "personalWorkGroup",
        query: { userId: userId, userName: userName }
      });
    },
    //确认分配角色
    assigningRoles() {
      let roleIds = [];
      let userIds = [];
      this.selectedGroup.map(item => {
        roleIds.push(item);
      });
      userIds.push(this.currentTokenUser.user.userId);
      let tem = { body: { roleIds: roleIds, userIds: userIds } };
      this.$store.dispatch("grantRoleUsingPOSTS", tem).then(() => {
        this.success("角色分配成功");
        this.setRoleStatus = false;
        this.getUserDetail(this.formInfo.origId);
      });
    },
    //选中角色
    selectGroup(group) {
      if (group.isActive == true) {
        group.isActive = false;
        let index = this.selectedGroup.indexOf(group.id);
        this.selectedGroup.splice(index, 1);
        return;
      }
      group.isActive = true;
      if (this.selectedGroup.indexOf(group.id) === -1) {
        this.selectedGroup.push(group.id);
      }
    },
    //查询角色
    setRole() {
      let pageSize = 30;
      this.$store
        .dispatch("roleListUsingPOSTS", { pageSize: pageSize })
        .then(ret => {
          this.setRoleStatus = true;
          this.groups = ret.data.records;
          this.groups.map((item, index) => {
            this.$set(item, "isActive", false);
          });
          let tem = this.currentTokenUser.roles;
          if (tem) {
            tem.map((group, index) => {
              this.groups.map((item, index) => {
                if (item.id === group.id) {
                  item.isActive = true;
                  if (this.selectedGroup.indexOf(group.id) === -1) {
                    this.selectedGroup.push(group.id);
                  }
                }
              });
            });
          }
        });
    },
    //app资源分配
    appResource() {
      // this.appResourceStatus = true;
      // this.$router.push({
      //   name: "appResource",
      //   query: { userId: this.formInfo.origId }
      // });
    },
    //确认导出excel
    sureExport() {},
    //确认调动部门
    async mobilizeOri() {
      if (this.chooseOrigId == "") {
        this.warning("请选择一个部门");
        return;
      }
      if (Array.isArray(this.chooseOrigId)) {
        this.chooseOrigId =
          this.chooseOrigId === null
            ? 0
            : this.chooseOrigId[this.chooseOrigId.length - 1];
      }
      let userIds = [];
      userIds.push(this.formInfo.origId);
      //是否删除原部门信息(true-删除,false-不删除)
      let type = true;
      let confirm = await this.confirmForm({
        title: "是否删除原部门信息",
        cancelText: "不删除",
        confirmText: "删除"
      });
      if (confirm == "cancel") {
        type = false;
      }
      const tem = {
        deptId: this.chooseOrigId,
        id: this.formInfo.userId
      };
      this.$store.dispatch("contactsDeptCopy", tem).then(ret => {
        this.success("调动部门成功");
        // this.getOrganizeUserRoot("ALL", 0, this.level, this.resolve);
        this.transferStatus = false;
        this.refreshLeftTreeData('all');
        // this.transferStatus = false;
      });
    },
    //关闭导出弹框
    exportExcelFail() {
      this.exportExcelContact = false;
    },
    //关闭新增用户弹窗
    fail() {
      this.addUserStatus = false;
      this.formInfo1 = { name: "", mobile: "" };
    },
    //关闭新增部门弹窗
    fail1() {
      this.addOrganizeStatus = false;
      this.formInfoOri = {
        name: "",
        sort: "",
        leaderName: "",
        leaderUserId: "",
        managerName: "",
        managerUserId: "",
        parentId: "",
        managerCustomId: "",
        leaderCustomId: ""
      };
      this.show1 = false;
      let t = setTimeout(() => {
        this.show1 = true;
      }, 0);
    },
    //添加部门
    addOri() {
      let formInfoOri = _.cloneDeep(this.formInfoOri);
      this.$refs["formOrig"].validate(valid => {
        if (valid) {
          formInfoOri.deleteFlag = "0";
          formInfoOri.parentId = formInfoOri.parentId[formInfoOri.parentId.length - 1];
          let {parentId} = formInfoOri;
          // if (Array.isArray(formInfoOri.id)) {
          //   formInfoOri.id =
          //     formInfoOri.id === null
          //       ? 0
          //       : formInfoOri.id[
          //           formInfoOri.id.length - 1
          //         ];
          // }
          let data = formInfoOri;
          for (let item in data) {
            if (data[item] === "") {
              delete data[item];
            }
          }
          this.API.addOrUpdateContactsDept({ body: data }).then(ret => {
            this.success("新增部门成功");
            this.fail1();
            if(parentId == 0){
              this.refreshLeftTreeData('all');
            }
            this.refreshLeftTreeData();
          });
        }
      });
    },
    //添加用户
    saveNewUser() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = {
            deptId: this.formInfo2.id,
            contacts: this.formInfo1,
            deptName: this.formInfo2.deptName
          };
          let userInfo1 = JSON.parse(sessionStorage.getItem("userInfo"));
          data.contacts.creator = userInfo1.user.name;
          // let data = this.formInfo1;
          // let tem = Object.assign({ orgId: this.formInfo.origId }, data);
          console.log(data);
          this.$store
            .dispatch("contactSaveUsingPOSTS", { body: data })
            .then(() => {
              console.log("___________");
              this.success("新增成功");
              this.refreshLeftTreeData();
              this.fail();
            });
        }
      });
    },
    //添加用户dialog
    addUser() {
      this.addUserStatus = true;
    },
    //添加部门dialog
    addOrganize() {
      console.log("当前的部门id是-------", this.formInfo.id);
      // this.formInfoOri.parentId = this.formInfo.id;
      this.addOrganizeStatus = true;
    },
    //获取部门列表(不包含用户)
    getDepartment() {
      this.API.gettreeContactsDept({ parentId: 0 }).then(ret => {
        if (ret.data) {
          console.log(ret.data);
          let resData = [];
          ret.data.map(item => {
            let conDept = {};
            Object.assign(conDept, item.contactsDept);
            // console.log(conDept.children)
            conDept.children = item.children;
            resData.push(conDept);
            console.log("8888888888", conDept);
          });
          this.departmentList = ret.data;
          console.log("97777777111111", this.departmentList);
        }
      });
    },
    //打开调动部门弹窗
    transfer() {
      this.transferStatus = true;
      this.API.getOrganizeTree({ parentId: 0, type: 0 }).then(ret => {
        this.getDepartment();
      });
    },
    exportExcel() {
      this.exportExcelContact = true;
    },
    //获取左侧tree
    refreshLeftTreeData(init) {
      if(init){
        this.getOrganizeUserRoot("ALL", 0, this.level, this.resolve);
        this.treeKey = new Date().getTime();
        return
      }
      let node = this.$refs.tree.getNode(this.node.data.id);
      // console.log(this.node.data.id, node);
      node.loaded = false;
      node.childNodes = [];
      node.expand();
    },
    //tree过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //修改用户信息
    addNewMenu() {
      this.$refs["newMenu"].validate(valid => {
        if (valid) {
          let param = {
            body: this.currentTokenUser.user
          };
          //  let param = {
          //   deptId : this.formInfo2.id,
          //   contacts : this.formInfo1
          // }
          // let userInfo1 = JSON.parse(sessionStorage.getItem("userInfo"));
          // data.contacts.creator = userInfo1.user.name;
          this.$store.dispatch("contactDeleteUsingPOSTS", param).then(ret => {
            this.success("保存成功");
            this.currentTokenUser.user = {};
            this.show = false;
            let t = setTimeout(() => {
              this.show = true;
            }, 0);
            this.refreshLeftTreeData();
          });
        } else {
          return false;
        }
      });
    },
    //排序
    handleSortCommand(val) {
      // console.log(val);
      this.sortType = val;
      this.sortDialogStatus = true;
      if (val == "org") {
        this.API.sortContactsDept({
          id: this.formInfo.id
        }).then(ret => {
          this.sortGroups = ret.data;
        });
      } else {
        this.API.sortPerson({
          id: this.formInfo.id
        }).then(ret => {
          this.sortGroups = ret.data;
        });
      }
      // if (this.formInfo.children) {
      //   this.sortGroups = this.formInfo.children.filter(item => {
      //     item.type == val;
      //   });
      // } else {

      // }
    },
    //删除部门信息
    handleCommand(command) {
      let title =
        command === 0
          ? "删除当前部门下的所有用户"
          : "删除部门下级节点的部门用户所有信息";
      this.$confirm("确定" + title + "?", "提示", {})
        .then(() => {
          let tem = {
            id: this.formInfo.id
          };
          if (command == 0) {
            //删除当前部门下人员
            this.API.deleteDeptPerson(tem).then(ret => {
              this.success("删除成功");
              this.refreshLeftTreeData();
            });
          } else {
            //对部门以及子部门下的人员进行删除
            this.API.deletePerson(tem).then(ret => {
              this.success("删除成功");
              this.refreshLeftTreeData();
            });
          }
        })
        .catch(() => {});
    },
    //删除部门
    deleteOri() {
      this.$confirm("确定删除当前部门？", "提示", {}).then(() => {
        let tem = {
          id: this.formInfo.id
        };
        this.node.data.id = this.formInfo.id;
        this.API.deleteContactsDeptById(tem).then(ret => {
          this.success("删除部门成功");
          this.refreshLeftTreeData('init');
        });
      });
    },
    //删除用户
    deleteUser() {
      this.$confirm("确认删除当前用户?", "提示", {})
        .then(() => {
          let tem = {
            id: this.formInfo.userId
            // orgId: this.formInfo.pid,
          };
          this.node.data.id = this.formInfo.parentId;
          this.$store.dispatch("userDelContactUsingDELETES", tem).then(() => {
            this.success("删除用户成功");
            this.refreshLeftTreeData();
          });
        })
        .catch(() => {});
    },
    //左侧tree点击事件
    handleNodeClick(val, Node, event) {
      this.formInfo = val;
      this.id = val.id;
      // console.log(val,Node,event)
      // console.log(this.formInfo.id, this.formInfo.type, this.formInfo.userId);

      if (this.formInfo.type == 0) {
        this.node.data.id = this.formInfo.id;
        //type为0获取部门信息
        this.getOrganize(this.formInfo.id);
      } else {
        this.node.data.id = this.formInfo.parentId;
        //获取用户信息
        this.getUserDetail(this.formInfo.userId);
      }
    },

    handleExpand(val) {
      this.formInfo = val;
      this.id = val.id;
      this.getOrganizeUserRoot(
        "ALL",
        this.formInfo.id,
        this.level,
        this.resolve
      );
    },

    //获取部门信息
    getOrganize(val) {
      if (this.formInfo2) {
        // this.formInfo2.leaderCustomId = "";
        this.formInfo2.managerCustomId = "";
      }
      console.log(val);
      this.API.getContactsDeptById({ id: val }).then(ret => {
        this.formInfo2 = ret.data;
        this.show = false;
        let t = setTimeout(() => {
          this.show = true;
        }, 0);
      });
    },
    //获取用户详情
    getUserDetail(val) {
      this.API.structure({ userId: val }).then(res => {
        this.currentDeptName = res.data.value;
      });
      this.API.getContactsById({ id: val }).then(ret => {
        this.currentTokenUser.user = ret.data;
        this.show = false;
        let t = setTimeout(() => {
          this.show = true;
        }, 0);
      });
    },
    //确认排序
    fixSort() {
      let arr = [];
      this.sortGroups.map(item => {
        arr.push(item.id);
      });
      if (this.sortType == "org") {
        this.API.updateSort({ body: { ids: arr } }).then(res => {
          this.refreshLeftTreeData();
          this.success("排序成功");
          this.sortDialogStatus = false;
        });
      } else {
        this.API.updateSort_1({ body: { ids: arr } }).then(res => {
          this.refreshLeftTreeData();
          this.success("排序成功");
          this.sortDialogStatus = false;
        });
      }
      // let type = this.sortGroups.every(item => item.type === "user");
      // let API = type ? "sortOrgUser" : "sortOrg";
      // let tem = type
      //   ? { orgId: this.formInfo.origId, userIds: arr }
      //   : { orgIds: arr };
      // this.API[API]({ body: tem }).then(() => {
      //   this.refreshLeftTreeData();
      //   this.success("排序成功");
      //   this.sortDialogStatus = false;
      // });
    },
    //关闭调动部门弹窗
    failOrganize() {
      this.chooseOrigId = "";
      this.transferStatus = false;
    }
  },
  components: {
    draggable
    // appResource
  }
};
</script>
<style scoped lang="less">
.flex-box {
  display: flex;
  .el-button {
    margin-left: 20px;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.input_content {
  float: left;
  width: 400px;
  height: auto;
  margin-right: 150px;
  box-sizing: border-box;
  font-size: 14px;
  /*color: #666666;*/
  text-align: left;
}

.holder-style {
  display: block;
  padding: 9px 16px;
  color: #aaa;
  background-color: #f1f1f1;
  outline: 2px dashed #d9d9d9;
  margin-bottom: 15px;
  border: 0;
  -webkit-transition: all 0.15s ease;
  -moz-transition: all 0.15s ease;
  transition: all 0.15s ease;
}

.holder-style:hover,
.holder-style:focus {
  cursor: pointer;
  color: #777;
  background-color: #eee;
  outline: 2px dashed #aaa;
  border: 0;
  text-decoration: none;
}

.holder-style.holder-active {
  background-color: #fff;
  outline-color: #70ca63;
}

.holder-style .holder-icon {
  color: #aaa;
  font-size: 30px;
  padding-bottom: 10px;
}

.holder-style:hover .holder-icon,
.holder-style:focus .holder-icon,
.holder-style.holder-active .holder-icon {
  color: #70ca63;
}

.span-ellipsis {
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.con /deep/ .el-card__body {
  padding: 0;
}

.sortCls {
  border: 1px solid #cecece;
  padding: 11px;
  margin-bottom: 6px;
  text-align: left;
  cursor: move;
}

.chosen {
  border: solid 2px #409eff !important;
}

.no-found-div {
  background: #f4faff;
  width: 100%;
  height: 120px;
  border: none;
}

.no-found-text {
  font-weight: bold;
  font-size: 24px;
  line-height: 120px;
  color: #333333;
  margin: 0 0 0 40px;
}

.container {
  display: flex;
  float: left;
  width: 100%;
  justify-content: space-between;
}

.left_item {
  width: 270px;
  min-height: 600px !important;
}

.right_item {
  width: calc(100% - 280px);
}

.app_res_dialog {
  /deep/ .el-dialog__body {
    padding: 0px 20px;
  }
}
</style>
